#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pyautogui
import time
import logging
import random
from datetime import datetime

# 设置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("binance_trading.log"),
        logging.StreamHandler()
    ]
)

class BinanceClickBot:
    def __init__(self):
        # 根据用户提供的准确坐标
        self.up_button = (178, 729)      # 上涨按钮坐标 (x, y) - 绿色按钮
        self.down_button = (333, 729)    # 下跌按钮坐标 (x, y) - 红色按钮
        self.amount_input = (147, 643)   # 金额输入框坐标
        self.amount_number = (260, 668)  # 输入法中金额数字位置
        self.done_button = (393, 529)    # 完成按钮坐标
        self.confirm_button = (260, 794) # 最终确认按钮坐标
        self.period_30m = (219, 574)     # 30m周期选择按钮坐标
        
        self.amount = "5"                 # 默认下注金额

    def click_button(self, position, button_name):
        """点击指定位置的按钮"""
        try:
            pyautogui.click(position)
            logging.info(f"点击了{button_name}按钮，坐标：{position}")
            return True
        except Exception as e:
            logging.error(f"点击{button_name}按钮失败: {str(e)}")
            return False

    def set_amount(self, amount=None):
        """设置下注金额"""
        if amount is None:
            amount = self.amount
            
        try:
            # 点击金额输入框
            self.click_button(self.amount_input, "金额输入框")
            time.sleep(0.5)
            
            # 点击输入法中的金额数字
            self.click_button(self.amount_number, "金额数字")
            time.sleep(0.5)
            
            # 点击完成按钮
            self.click_button(self.done_button, "完成按钮")
            time.sleep(0.5)
            
            logging.info(f"设置金额为: {amount}")
            return True
        except Exception as e:
            logging.error(f"设置金额失败: {str(e)}")
            return False

    def predict_trend(self):
        """
        根据策略决定是看涨还是看跌
        返回: 1 (看涨), -1 (看跌), 0 (不交易)
        """
        # 这里替换为您的交易策略
        # 示例：简单随机策略
        # return random.choice([1, -1])
        
        # 示例：时间策略 - 偶数分钟看涨，奇数分钟看跌
        current_minute = datetime.now().minute
        if current_minute % 2 == 0:
            return 1  # 看涨
        else:
            return -1  # 看跌

    def run(self, check_interval=10, trade_interval=300):
        """
        运行交易机器人
        check_interval: 检查间隔时间(秒)
        trade_interval: 交易间隔时间(秒)
        """
        last_trade_time = 0
        
        logging.info("币安自动交易程序启动...")
        
        while True:
            try:
                current_time = time.time()
                
                # 检查是否应该交易
                if current_time - last_trade_time >= trade_interval:
                    direction = self.predict_trend()
                    
                    if direction != 0:
                        # 点击30m周期
                        self.click_button(self.period_30m, "30m周期")
                        time.sleep(1)
                        
                        # 设置金额
                        self.set_amount()
                        time.sleep(1)
                        
                        # 执行交易 - 点击上涨或下跌按钮
                        if direction == 1:
                            success = self.click_button(self.up_button, "上涨")
                        else:
                            success = self.click_button(self.down_button, "下跌")
                        
                        time.sleep(1)
                        
                        # 点击最终确认按钮
                        if success:
                            self.click_button(self.confirm_button, "确认按钮")
                            last_trade_time = current_time
                            logging.info(f"交易执行成功，方向: {'上涨' if direction == 1 else '下跌'}")
                            # 交易后休息一段时间
                            time.sleep(5)
                
                # 休息一段时间后再次检查
                logging.info(f"等待 {check_interval} 秒后进行下一次检查")
                time.sleep(check_interval)
                
            except KeyboardInterrupt:
                logging.info("程序被用户中断，正在退出...")
                break
            except Exception as e:
                logging.error(f"发生错误: {str(e)}")
                time.sleep(10)  # 出错后等待

if __name__ == "__main__":
    # 给用户一些时间准备
    print("程序将在5秒后开始运行，请确保币安APP在前台显示...")
    for i in range(5, 0, -1):
        print(f"{i}...")
        time.sleep(1)
    
    bot = BinanceClickBot()
    
    # 开始运行，每30秒检查一次，每5分钟最多交易一次
    bot.run(check_interval=10, trade_interval=10)